export function chooseContact() {
	return new Promise((resolve, reject) => {
		// **微信小程序**
		// #ifdef MP-WEIXIN
		wx.chooseContact({
			success: result => {
				resolve({
					name: result.displayName,
					tel: result.phoneNumber
				});
			},
			fail: reject
		});
		return;
		// #endif

		// **App 端 (Android / iOS)**
		// #ifdef APP-PLUS
		handleContactPermission()
			.then(selectContact)
			.then(resolve)
			.catch(reject);
		return;
		// #endif

		// **H5 / 其他平台**
		// #ifndef APP-PLUS || MP-WEIXIN
		reject(new Error("当前平台不支持 chooseContact"));
		// #endif
	});
}

/** 处理通讯录权限 (App 端) */
function handleContactPermission() {
	return new Promise((resolve, reject) => {
		if (!plus || !plus.os) {
			reject(new Error("plus API 不可用"));
			return;
		}

		// Android 权限检测
		if (plus.os.name === "Android") {
			const main = plus.android.runtimeMainActivity();
			const Context = plus.android.importClass("android.content.Context");
			const PackageManager = plus.android.importClass("android.content.pm.PackageManager");
			const permission = "android.permission.READ_CONTACTS";
			
			// 检查权限
			if (main.checkSelfPermission(permission) !== PackageManager.PERMISSION_GRANTED) {
				plus.android.requestPermissions([permission], (e) => {
					if (e.granted.length > 0) {
						resolve();
					} else {
						reject(new Error("用户拒绝通讯录权限"));
					}
				});
			} else {
				resolve();
			}
		} 
		// iOS 权限检测
		else if (plus.os.name === "iOS") {
			const CNContactStore = plus.ios.import("CNContactStore");
			const store = new CNContactStore();
			const authStatus = store.authorizationStatusForEntityType(0);

			if (authStatus === 3) { // 已授权
				resolve();
			} else {
				store.requestAccessForEntityTypeCompletionHandler(0, (granted) => {
					granted ? resolve() : reject(new Error("用户拒绝通讯录权限"));
				});
			}
		} else {
			reject(new Error("不支持的操作系统"));
		}
	});
}

/** 选择联系人 (App 端) */
function selectContact() {
	return new Promise((resolve, reject) => {
		if (!plus || !plus.os) {
			reject(new Error("plus API 不可用"));
			return;
		}

		// iOS 设备
		if (plus.os.name === "iOS") {
			const contactPickerVC = plus.ios.newObject("CNContactPickerViewController");
			const delegate = plus.ios.implements("CNContactPickerDelegate", {
				"contactPicker:didSelectContact:": (picker, contact) => {
					let name = (contact.plusGetAttribute("familyName") || "") + (contact.plusGetAttribute("givenName") || "");
					let phoneNo = "";

					let phones = contact.plusGetAttribute("phones");
					if (phones.plusGetAttribute("count") > 0) {
						let phone = phones.plusGetAttribute("firstObject").plusGetAttribute("value");
						phoneNo = phone.plusGetAttribute("stringValue");
					}

					resolve({ name, tel: phoneNo });
				}
			});

			plus.ios.invoke(contactPickerVC, "setDelegate:", delegate);
			const currentWebview = plus.ios.currentWebview();
			const currentVC = getViewControllerByView(currentWebview);
			plus.ios.invoke(currentVC, "presentViewController:animated:completion:", contactPickerVC, true, null);
		} 
		
		// Android 设备
		else if (plus.os.name === "Android") {
			let REQUESTCODE = 1000;
			const main = plus.android.runtimeMainActivity();
			const Intent = plus.android.importClass("android.content.Intent");
			const ContactsContract = plus.android.importClass("android.provider.ContactsContract");
			const intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);

			main.onActivityResult = function (requestCode, resultCode, data) {
				if (REQUESTCODE !== requestCode) {
					reject('获取失败')
					return
				}

				try {
					plus.android.importClass(data);
					const resolver = main.getContentResolver();
					plus.android.importClass(resolver);

					const cursor = resolver.query(data.getData(), null, null, null, null);
					plus.android.importClass(cursor);
					if (!cursor || !cursor.moveToFirst()) {
						reject(new Error("未选择联系人"));
						return;
					}

					let name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)) || "";
					let contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
					let phoneNo = "";

					let pCursor = resolver.query(
						ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
						null,
						ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId,
						null,
						null
					);

					if (pCursor.moveToNext()) {
						phoneNo = pCursor.getString(pCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
					}

					resolve({ name, tel: phoneNo });
					cursor.close();
					pCursor.close();
				} catch (error) {
					reject(error);
				}
			};

			main.startActivityForResult(intent, REQUESTCODE);
		} else {
			reject(new Error("不支持的操作系统"));
		}
	});
}

/** 获取 iOS 当前 ViewController */
function getViewControllerByView(view) {
	const UIWebViewClass = plus.ios.importClass("UIWebView");
	const UIViewControllerClass = plus.ios.importClass("UIViewController");

	if (view.isKindOfClass(UIWebViewClass)) {
		return plus.ios.invoke(view, "window", "rootViewController");
	} else {
		return plus.ios.invoke(view, "rootViewController");
	}
}
